package com.hxd.otc.module.my.activity;

import android.annotation.SuppressLint;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;

import com.hxd.otc.R;
import com.hxd.otc.base.BaseActivity;
import com.hxd.otc.common.RecentLoginAccountInfoHelper;
import com.hxd.otc.common.UserHelper;
import com.hxd.otc.common.enums.CardLevelEnum;
import com.hxd.otc.common.enums.ExValidType;
import com.hxd.otc.common.enums.IdCardStatusEnum;
import com.hxd.otc.dialog.ExValidTypeInputDialog;
import com.hxd.otc.dialog.FingerprintIdentifyDialog;
import com.hxd.otc.dialog.ForbiddenBankCardDialog;
import com.hxd.otc.dialog.MultipleBlocksDialog;
import com.hxd.otc.dialog.SelectExValidTypeDialog;
import com.hxd.otc.event.Event;
import com.hxd.otc.module.my.bean.UserStatusBean;
import com.hxd.otc.module.my.contract.SecurityCenterContract;
import com.hxd.otc.module.my.presenter.SecurityCenterPresenter;
import com.hxd.otc.utils.CommonUtil;
import com.hxd.otc.utils.ResourceUtil;
import com.hxd.otc.utils.UIUtils;
import com.hxd.otc.widget.BlocksToast;
import com.hxd.otc.widget.SecurityCenterItemView;
import com.wei.android.lib.fingerprintidentify.FingerprintIdentify;
import com.wei.android.lib.fingerprintidentify.base.BaseFingerprint;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;

/**
 * Created by lzy on 2018/6/12 0012.
 * description ${安全中心}
 */
public class SecurityCenterActivity extends BaseActivity<SecurityCenterPresenter> implements SecurityCenterContract.View {

    @BindView(R.id.sciv_money_password)
    SecurityCenterItemView mScivMoneyPassword;
    @BindView(R.id.sciv_phone_number)
    SecurityCenterItemView mScivPhoneNumber;
    @BindView(R.id.sciv_login_password)
    SecurityCenterItemView mScivLoginPassword;
    @BindView(R.id.sciv_bind_email)
    SecurityCenterItemView mScivBindEmail;
    @BindView(R.id.sciv_real_name_auth)
    SecurityCenterItemView mScivRealNameAuth;
    @BindView(R.id.sciv_google_auth)
    SecurityCenterItemView mScivGoogleAuth;
    @BindView(R.id.sciv_changed_ex_valid_type)
    SecurityCenterItemView mScivExValidType;
    @BindView(R.id.sciv_fingerprint_password)
    SecurityCenterItemView mScivFingerprintPassword;

    private ForbiddenBankCardDialog<String> mRealNameAuthFailTipDialog;
    private SelectExValidTypeDialog mSelectExValidTypeDialog;
    private ExValidTypeInputDialog mExValidTypeInputDialog;
    private String mReason;
    private FingerprintIdentifyDialog mFingerprintIdentifyDialog;
    private FingerprintIdentify mFingerprintIdentify;
    private MultipleBlocksDialog warmTipDialog;


    private ForbiddenBankCardDialog<String> mGoToSetFingerprintDialog;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_security_center;
    }

    @Override
    protected void initView() {
        registerEventBus();
        updatePhoneNumber();
        updateEmail();
        updatePayPassword();
        updateCardStatus();
        updateGoogle();
        updateExValidType();
        initFingerprintPassword();
    }


    @Override
    protected void initData() {
        mPresenter.findCardStatus();
    }

    @Override
    protected void initEvent() {
    }

    @Override
    protected SecurityCenterPresenter createPresenter() {
        return new SecurityCenterPresenter(this);
    }

    @OnClick({R.id.sciv_money_password, R.id.sciv_phone_number, R.id.sciv_login_password, R.id.sciv_bind_email,
            R.id.sciv_real_name_auth, R.id.sciv_google_auth, R.id.sciv_changed_ex_valid_type, R.id.sciv_fingerprint_password})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.sciv_phone_number://绑定手机号
                onChangePhone();
                break;
            case R.id.sciv_bind_email://绑定邮箱
                onBindEmail();
                break;
            case R.id.sciv_money_password://交易密码
                onSetPayPassword();
                break;
            case R.id.sciv_real_name_auth://实名认证
                onRealNameAuth();
                break;
            case R.id.sciv_google_auth://谷歌认证
                onGoogleAuth();
                break;
            case R.id.sciv_login_password://登录密码
                $startActivity(ModifyLoginPasswordActivity.class);
                break;
            case R.id.sciv_changed_ex_valid_type://修改交易验证方式
                showWarmTipDialog();
                break;
            case R.id.sciv_fingerprint_password://指纹密码
                onFingerprintPassword();
                break;
        }
    }

    private void showWarmTipDialog() {
        if (warmTipDialog == null) {
            warmTipDialog = new MultipleBlocksDialog(this);
            warmTipDialog.setTitle(getString(R.string.warm_tips))
                    .setContent(getString(R.string.warm_tips_hint))
                    .setOnDialogItemClickListener(new MultipleBlocksDialog.OnDialogItemClickListener() {
                        @Override
                        public void onSure() {
                            showSelectExValidTypeDialog();
                        }

                        @Override
                        public void onCancel() {
                            warmTipDialog.dismiss();
                        }
                    });
        }
        warmTipDialog.show();
    }

    /**
     * 指纹密码
     */
    private void onFingerprintPassword() {
        //重新初始化，更新状态
        mFingerprintIdentify.init();
        //当用户硬件支持指纹，但是还没有注册指纹，则引导到设置界面进行设置
        if (!mFingerprintIdentify.isRegisteredFingerprint()) {
            showGoToSetFingerprintDialog();
            return;
        }

        boolean toggleTurnOn = mScivFingerprintPassword.isToggleTurnOn();
        if (toggleTurnOn) {
            updateFingerprintStatus(false);
            showToast(getString(R.string.fingerprint_login_has_been_turned_off));
        } else {
            showFingerprintPasswordDialog();
        }
    }

    @NonNull
    private void showGoToSetFingerprintDialog() {
        if (mGoToSetFingerprintDialog == null) {
            mGoToSetFingerprintDialog = new ForbiddenBankCardDialog<>(this);
        } else {
            UIUtils.dismissDialog(mGoToSetFingerprintDialog);
        }

        mGoToSetFingerprintDialog.setMessage(getString(R.string.you_have_not_set_the_fingerprint_whether_to_go_to_the_settings))
                .setConfirmText(getString(R.string.yes))
                .setCancleText(getString(R.string.deny))
                .setOnConfirmClickListener(new ForbiddenBankCardDialog.OnConfirmClickListener<String>() {
                    @Override
                    public void onConfirm(String data) {
                        CommonUtil.startSettingActivity(SecurityCenterActivity.this);
                    }
                }).show();
    }

    private void showFingerprintPasswordDialog() {
        if (mFingerprintIdentifyDialog == null) {
            createFingerprintPasswordDialog();
        } else {
            UIUtils.dismissDialog(mFingerprintIdentifyDialog);
        }
        mFingerprintIdentifyDialog.show();
    }

    private void createFingerprintPasswordDialog() {
        mFingerprintIdentifyDialog = new FingerprintIdentifyDialog(this)
                .setTitleText(getString(R.string.app_name) + getString(R.string.verify))
                .setContentText(getString(R.string.please_verify_your_mobile_phone_fingerprint))
                .setIdentifyListener(new BaseFingerprint.IdentifyListener() {
                    @Override
                    public void onSucceed() {
                        UIUtils.dismissDialog(mFingerprintIdentifyDialog);
                        updateFingerprintStatus(true);
                        showToast(getString(R.string.fingerprint_login_has_been_turned_on));
                    }

                    @Override
                    public void onNotMatch(int i) {
                    }

                    @Override
                    public void onFailed(boolean b) {
                    }

                    @Override
                    public void onStartFailedByDeviceLocked() {
                    }
                });
    }

    /**
     * 更新指纹状态
     *
     * @param fingerprintStatus
     */
    private void updateFingerprintStatus(boolean fingerprintStatus) {
        mScivFingerprintPassword.setToggleStatus(fingerprintStatus);
        RecentLoginAccountInfoHelper.updateFingerprintStatus(fingerprintStatus);
    }


    /**
     * 修改手机号
     */
    private void onChangePhone() {
        $startActivity(ChangePhoneActivity.class);
    }

    /**
     * 绑定邮箱
     */
    private void onBindEmail() {
        if (UserHelper.isBoundEmail()) {
            showToast(getString(R.string.user_account_mail_bind));
        } else {
            $startActivity(BindEmailActivity.class);
        }
    }

    /**
     * 设置交易密码
     */
    private void onSetPayPassword() {
        if (!UserHelper.isBoundPhone()) {
            showToast(getString(R.string.please_bind_the_phone_number_first));
            return;
        }
        if (UserHelper.isSetPayPassword()) {
            showToast(getString(R.string.user_trade_not_update));
        } else {
            $startActivity(ModifyMoneyPasswordActivity.class);
        }
    }

    /**
     * 实名认证
     */
    private void onRealNameAuth() {
        switch (UserHelper.getCardStatus()) {
            case Unverified:
                $startActivity(CertificationTypeActivity.class);
                break;
            case V1_Verified:
            case V2_Verified:
                $startActivity(CertificationDetailActivity.class);
                break;
            case V1_AuthFaild:
            case V2_AuthFaild:
                showRealNameAuthFailReasonDialog(mReason);
                break;
            case V1_Auditing:
            case V2_Auditing:
                showToast(getString(R.string.account_auditing_submit));
                break;
        }
    }


    /**
     * 谷歌认证
     */
    private void onGoogleAuth() {
        if (UserHelper.isSetGoogleAuth()) {
            showToast(getString(R.string.account_auditing_success));
        } else {
            $startActivity(BindGoogleCodeActivity.class);
        }
    }

    private void showExValidTypeInputDialog(final ExValidType newExValidType) {
        if (mExValidTypeInputDialog == null) {
            mExValidTypeInputDialog = new ExValidTypeInputDialog(this);
        }
        mExValidTypeInputDialog.setExValidType(UserHelper.getExValidType())
                .setOnExValidTypeListener(new ExValidTypeInputDialog.OnExValidTypeListener() {
                    @Override
                    public void onVerCode(String verCode) {
                        mPresenter.changeExValidType(newExValidType, verCode);
                    }

                    @Override
                    public void getVerCode(ExValidType curExValidType) {
                        if (ExValidType.GoogleAuth.equals(curExValidType)) {
                            showExValidTypeInputDialog(newExValidType);
                        } else if (ExValidType.SMS.equals(curExValidType)) {//需要发送短信验证码
                            mPresenter.sendSetVerifyModeSms(newExValidType);
                        } else if (ExValidType.Email.equals(curExValidType)) {
                            mPresenter.sendExValidTypeEmail(newExValidType);
                        } else {
                            mPresenter.onSetExValidType(newExValidType);//还没有设置就直接设置
                        }
                    }
                }).show();
    }

    private void showSelectExValidTypeDialog() {
        if (mSelectExValidTypeDialog == null)
            mSelectExValidTypeDialog = new SelectExValidTypeDialog(this)
                    .setOnSelectExValidTypeListener(new SelectExValidTypeDialog.OnSelectExValidTypeListener() {
                        @Override
                        public void onSetExValidType(ExValidType newExValidType) {
                            ExValidType curExValidType = UserHelper.getExValidType();
                            if (ExValidType.GoogleAuth.equals(curExValidType)) {
                                showExValidTypeInputDialog(newExValidType);
                            } else if (ExValidType.SMS.equals(curExValidType)) {//需要发送短信验证码
                                showExValidTypeInputDialog(newExValidType);
//                                mPresenter.sendSetVerifyModeSms(newExValidType);
                            } else if (ExValidType.Email.equals(curExValidType)) {
                                showExValidTypeInputDialog(newExValidType);
//                                mPresenter.sendExValidTypeEmail(newExValidType);
                            } else {
                                mPresenter.onSetExValidType(newExValidType);//还没有设置就直接设置
                            }
                        }
                    });
        mSelectExValidTypeDialog.show();
    }

    @Override
    public void getVerifyModeSmsSuccess(ExValidType newExValidType) {
        showToast(getString(R.string.phone_sms_already_send_to_your_bound_phone));
        startCountdown();
        showExValidTypeInputDialog(newExValidType);
    }

    @Override
    public void getVerifyModeEmailSuccess(ExValidType newExValidType) {
        BlocksToast.get().showToast(R.string.email_ver_code_already_send_to_your_bound_email);
        startCountdown();
        showExValidTypeInputDialog(newExValidType);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateAccountInfoEvent(Event.UserInfoUpdateEvent userInfoUpdateEvent) {
        updatePhoneNumber();
        updateEmail();
        updatePayPassword();
        updateCardStatus();
        updateGoogle();
        updateExValidType();
        initFingerprintPassword();
    }

    private void updateGoogle() {
        mScivGoogleAuth.setRightText(getString(UserHelper.isSetGoogleAuth() ? R.string.verified : R.string.unverified));
        mScivGoogleAuth.setRightTextColor(ResourceUtil.getColor(UserHelper.isSetGoogleAuth() ? R.color.color_FF95A2AC : R.color.color_FFEE5344));
    }

    private void updateCardStatus() {
        IdCardStatusEnum cardStatus = UserHelper.getCardStatus();
        mScivRealNameAuth.setRightText(cardStatus.getDesc());
        mScivRealNameAuth.setRightTextColor(ResourceUtil.getColor(
                (cardStatus == IdCardStatusEnum.V1_Verified || cardStatus == IdCardStatusEnum.V2_Verified) ? R.color.color_FF95A2AC :
                        (cardStatus == IdCardStatusEnum.V1_Auditing || cardStatus == IdCardStatusEnum.V2_Auditing) ?
                                R.color.color_FFF09536 :
                                R.color.color_FFEE5344));
    }

    private void updatePayPassword() {
        mScivMoneyPassword.setRightText(getString(UserHelper.isSetPayPassword() ? R.string.my_reset : R.string.not_set));
        mScivMoneyPassword.setRightTextColor(ResourceUtil.getColor(UserHelper.isSetPayPassword() ? R.color.color_FF464E5F : R.color.color_FFEE5344));
    }

    private void updateEmail() {
        mScivBindEmail.setRightText(UserHelper.isBoundEmail() ? UserHelper.getEmail() : getString(R.string.not_bound));
        mScivBindEmail.setRightTextColor(ResourceUtil.getColor(UserHelper.isBoundEmail() ? R.color.color_FF95A2AC : R.color.color_FFEE5344));
    }

    private void updatePhoneNumber() {
        mScivPhoneNumber.setRightText(UserHelper.isBoundPhone() ? UserHelper.getMobile() : getString(R.string.not_bound));
        mScivPhoneNumber.setRightTextColor(ResourceUtil.getColor(UserHelper.isBoundPhone() ? R.color.color_FF464E5F : R.color.color_FFEE5344));
    }

    private void updateExValidType() {
        ExValidType exValidType = UserHelper.getExValidType();
        mScivExValidType.setRightText(exValidType.getDesc());
        mScivExValidType.setRightTextColor(ResourceUtil.getColor(ExValidType.Other.equals(exValidType) ? R.color.color_FFEE5344 : R.color.color_FF464E5F));
    }

    /**
     * 初始化指纹密码设置
     */
    private void initFingerprintPassword() {

        //作为v1.1.7-->v1.1.8升级跨越时，已登录用户对于指纹开关兼容的配置检测，用以屏蔽指纹功能，
        // 因为此时没有缓存的登录密码,所以暂不显示，等重新再次登录后即可
        if (!RecentLoginAccountInfoHelper.isSupport()) {
            mScivFingerprintPassword.setVisibility(View.GONE);
            return;
        }

        //当硬件不支持时，则不显示该功能
        mFingerprintIdentify = new FingerprintIdentify(getApplicationContext());
        mFingerprintIdentify.setSupportAndroidL(true);
        mFingerprintIdentify.init();
        if (!mFingerprintIdentify.isHardwareEnable()) {
            mScivFingerprintPassword.setVisibility(View.GONE);
            return;
        }
        //当硬件支持则显示指纹密码功能
        mScivFingerprintPassword.setVisibility(View.VISIBLE);
        mScivFingerprintPassword.setBackgroundResource(android.R.color.white);
        mScivFingerprintPassword.setToggleStatus(RecentLoginAccountInfoHelper.isFingerprintStatus());
    }

    @Override
    public void findCardStatusSuccess(UserStatusBean userStatusBean) {

        if (userStatusBean == null) return;

        UserHelper.updateCardStatus(IdCardStatusEnum.getIDCardStatusEnum(userStatusBean.getCardStatus()));

        mReason = userStatusBean.getReason();
        if (TextUtils.isEmpty(mReason)) {
            mReason = getString(R.string.unknown);
        }
    }

    @Override
    public void findCardStatusFail(String errMessage) {
        mReason = getString(R.string.unknown);
    }

    private void showRealNameAuthFailReasonDialog(String reason) {
        String content = String.format(getString(R.string.real_name_auth_fail_reason_mode), reason);

        if (mRealNameAuthFailTipDialog == null) {
            mRealNameAuthFailTipDialog = new ForbiddenBankCardDialog<String>(this);
        } else if (mRealNameAuthFailTipDialog.isShowing()) {
            mRealNameAuthFailTipDialog.dismiss();
        }
        mRealNameAuthFailTipDialog.setTitle(getString(R.string.real_name_auth_tip_title))
                .setMessage(content)
                .setConfirmText(getString(R.string.confirm))
                .setOnConfirmClickListener(new ForbiddenBankCardDialog.OnConfirmClickListener<String>() {
                    @Override
                    public void onConfirm(String data) {
                        //当前已经进行lv1认证，则直接进入lv2认证,没有仅重新进行认证类型选择
                        $startActivity(CardLevelEnum.LEVEL_1.equals(UserHelper.getCardLevel()) ? RealNameStep1Activity.class : CertificationTypeActivity.class);
                    }
                }).show();
    }


    @Override
    public void setValidTypeSuccess(ExValidType exValidType) {
        showToast(getString(R.string.modify_ex_valid_type_success));
        UserHelper.updateExValidType(exValidType);
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
            mDisposable = null;
        }
    }

    private Disposable mDisposable;

    /**
     * 开始倒计时
     */
    public void startCountdown() {
        if (mExValidTypeInputDialog == null || mExValidTypeInputDialog.getmTvSendVerCode() == null)
            return;
        //从0开始发射11个数字为：0-10依次输出，延时0s执行，每1s发射一次。
        mExValidTypeInputDialog.getmTvSendVerCode().setEnabled(false);
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
            mDisposable = null;
        }
        mDisposable = Flowable.intervalRange(0, 60, 0, 1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(new io.reactivex.functions.Consumer<Long>() {
                    @SuppressLint("DefaultLocale")
                    @Override
                    public void accept(Long aLong) {
                        mExValidTypeInputDialog.getmTvSendVerCode().setText(String.format("%ds", 60 - aLong));
                    }
                })
                .doOnComplete(new Action() {
                    @Override
                    public void run() {
                        //倒计时完毕置为可点击状态
                        mExValidTypeInputDialog.getmTvSendVerCode().setEnabled(true);
                        mExValidTypeInputDialog.getmTvSendVerCode().setText(R.string.send_message_code);
                    }
                })
                .subscribe();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        UIUtils.dismissDialog(mSelectExValidTypeDialog);
        UIUtils.dismissDialog(mGoToSetFingerprintDialog);
        UIUtils.dismissDialog(warmTipDialog);
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
            mDisposable = null;
        }
    }
}
